﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace CodeSystem.Tool.Helpers
{
    /// <summary>
    /// 加密算法帮助类
    /// </summary>
    public static class HashHelper
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">要加密的值</param>
        /// <param name="format">格式，默认为16进制x2</param>
        /// <returns>密文</returns>
        public static string Md5(string str, string format = "x2")
        {
            var hash = MD5.Create();
            var hashBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(str));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString(format));
            }
            return sb.ToString();
        }

        /// <summary>
        /// Sha1加密
        /// </summary>
        /// <param name="str">要加密的值</param>
        /// <param name="format">格式，默认为16进制x2</param>
        /// <returns>密文</returns>
        public static string Sha1(string str, string format = "x2")
        {
            var hash = SHA1.Create();
            var hashBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(str));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString(format));
            }
            return sb.ToString();
        }

        /// <summary>
        /// Sha256加密
        /// </summary>
        /// <param name="str">要加密的值</param>
        /// <param name="format">格式，默认为16进制x2</param>
        /// <returns>密文</returns>
        public static string Sha256(string str, string format = "x2")
        {
            var hash = SHA256.Create();
            var hashBytes = hash.ComputeHash(Encoding.UTF8.GetBytes(str));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hashBytes.Length; i++)
            {
                sb.Append(hashBytes[i].ToString(format));
            }
            return sb.ToString();
        }
    }
}
